<?php

namespace Boosen\Admin\Menus\Models;

use Encore\Admin\Traits\AdminBuilder;
use Encore\Admin\Traits\ModelTree;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Support\Facades\DB;

/**
 * Class Menu.
 *
 * @property int $id
 *
 * @method where($parent_id, $id)
 */
class Menu extends Model
{
    use ModelTree;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['name', 'slug'];

    protected $table = 'boosen_menus';
    /**
     * Create a new Eloquent model instance.
     *
     * @param array $attributes
     */
    public function __construct(array $attributes = [])
    {
        $connection = config('admin.database.connection') ?: config('database.default');

        $this->setConnection($connection);

        $this->setTable(config('menus.menus_table', $this->table));

        parent::__construct($attributes);
    }

    public function getItemsTree()
    {
        $items = MenuItem::where('menu_id', $this->id)->orderBy('order', 'asc')->get()->toArray();
        return $this->buildChildren($items);
    }


    private function buildChildren($nodes = [], $pid = 0)
    {
        $branch = [];

        if (empty($nodes)) {
            return $nodes;
        }


        foreach ($nodes as $node) {
            if ($node['parent_id'] == $pid) {
                $children = $this->buildNestedArray($nodes, $node['id']);

                if ($children) {
                    $node['children'] = $children;
                }

                $branch[] = $node;
            }
        }

        return $branch;
    }
}
